import time
from celery import Celery
import os

if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'electricity_supplier_project.settings'
app = Celery('tasks', broker='redis://guest@localhost:6379//')


@app.task
def check_orderinfo(id):
    print("异步任务开始调用")
    # 客户生成订单30分钟后未支付，自动将该订单取消
    time.sleep(60*30)
    from goods.models import GoodsAttribute, Goods, DiscountPackage
    from orders.models import OrderGoods, DiscountCoupon
    from orders.models import OrderInfo
    orderinfo = OrderInfo.objects.get(order_id=id)
    if orderinfo.status == 1:
        goods_list = OrderGoods.objects.filter(order=orderinfo)
        for order_goods in goods_list:
            # 更改商品属性对象的库存
            storage_amout = GoodsAttribute.objects.get(id=order_goods.goods.id).storage_amout
            new_storage_amout = storage_amout + order_goods.count
            ret_2 = GoodsAttribute.objects.filter(id=order_goods.goods.id).update(
                storage_amout=new_storage_amout)  # 更新商品属性的库存
            # 更改商品对象的销量
            sold_num = Goods.objects.get(id=order_goods.goods.goods.id).sold_num
            new_sold_num = sold_num - order_goods.count
            ret_3 = Goods.objects.filter(id=order_goods.goods.goods.id).update(sold_num=new_sold_num)  # 更新商品销量
        # 如果该订单使用了优惠券，将优惠券数量变更回去，用户绑定的优惠券对象状态变更
        if orderinfo.discountcoupon:
            ret_4 = DiscountCoupon.objects.filter(id=orderinfo.discountcoupon.id).update(status=False,
                                                                                         is_show=True)  # 更新客户绑定的优惠券
            used_counts = DiscountCoupon.objects.get(name=orderinfo.discountcoupon.name, user=None).used_counts
            new_used_counts = used_counts - 1
            ret_5 = DiscountCoupon.objects.filter(name=orderinfo.discountcoupon.name, user=None,
                                                  used_counts=used_counts).update(
                used_counts=new_used_counts)  # 更新该类型优惠券使用量
        if orderinfo.discountpackage:
            new_number = orderinfo.discountpackage.number - 1
            ret_6 = DiscountPackage.objects.filter(id=orderinfo.discountpackage.id).update(number=new_number)
        orderinfo.status = 6
        orderinfo.save()


@app.task
def check_return(id):
    from orders.models import ReturnDetail
    # 客户申请售后，3天后未处理，默认同意申请
    time.sleep(60*60*24*3)
    return_detail = ReturnDetail.objects.get(id=id)
    if return_detail.check_results == 0:
        if return_detail.order_goods_id.is_return == 1:
            return_detail.check_results = 2
        if return_detail.order_goods_id.is_return == 3:
            return_detail.check_results = 4
        if return_detail.order_goods_id.is_return == 5:
            return_detail.check_results = 8
        if return_detail.order_goods_id.is_return == 7:
            return_detail.check_results = 6
    else:
        pass


"""celery运行命令，在tasks路径下: celery -A tasks worker --loglevel=info"""
